// recipeEdit.js
const app = getApp(); // 添加获取app实例

Page({
  data: {
    recipeId: null,
    isEdit: false,
    categoryId: null,
    categories: [],
    difficultyOptions: ['简单', '中等', '困难'],
    // 添加单位选项
    unitOptions: ['g', 'kg', 'ml', 'L', '个', '勺', '杯', '少许'],
    recipe: {
      name: '',
      categoryId: '',
      difficulty: '中等',
      time: '',
      mainIngredients: [{ name: '', amount: '', unit: 'g' }],
      additionalIngredients: [],
      steps: [{
        materials: [{ name: '', amount: '' }],
        desc: '',
        result: '',
        resultName: '',
        time: ''
      }],
      tips: '',
      imageUrl: ''
    },
    showImagePicker: false,
    // 选中的材料项
    selectedIngredient: {
      type: '',
      index: -1
    },
    // 材料编辑器弹窗
    showIngredientEditor: false,
    editorData: {
      type: '',
      index: -1,
      name: '',
      amount: '',
      unit: 'g'
    }
  },

  onLoad: function(options) {
    const { id, categoryId } = options;
    
    // 初始化默认数据结构
    const defaultRecipe = {
      name: '',
      categoryId: '',
      difficulty: '中等',
      time: '',
      mainIngredients: [{ name: '', amount: '', unit: 'g' }],
      additionalIngredients: [],
      steps: [{
        materials: [{ name: '', amount: '' }],
        desc: '',
        result: '',
        resultName: '',
        time: ''
      }],
      tips: '',
      imageUrl: ''
    };

    // 设置初始数据
    this.setData({
      recipe: defaultRecipe
    });
    
    // 加载分类数据
    this.loadCategories();
    
    if (id) {
      // 编辑现有配方
      this.setData({ 
        recipeId: id,
        isEdit: true 
      });
      this.loadRecipeDetail(id);
    } else if (categoryId) {
      // 添加新配方，预选分类
      this.setData({
        categoryId,
        'recipe.categoryId': categoryId
      });
    }
    
    // 添加WxsPreviousResults计算属性，使getPreviousResults方法在WXML中可用
    this.setData({
      wxsGetPreviousResults: (index) => {
        return this.getPreviousResults(index);
      }
    });
  },

  onShow: function() {
    // 页面显示时，打印调试信息
    console.log('页面显示 - 弹窗状态:', this.data.showIngredientEditor);
  },

  // 加载分类数据
  loadCategories() {
    if (app.globalData && app.globalData.categories) {
      this.setData({
        categories: app.globalData.categories
      });
    }
  },

  loadRecipeDetail(id) {
    try {
      const allRecipes = app.globalData.recipes || [];
      const recipe = allRecipes.find(r => r.id.toString() === id.toString());
      
      if (recipe) {
        // 确保所有必要的数组属性都存在
        const recipeWithDefaults = {
          ...recipe,
          mainIngredients: Array.isArray(recipe.mainIngredients) ? recipe.mainIngredients : [{ name: '', amount: '', unit: 'g' }],
          additionalIngredients: Array.isArray(recipe.additionalIngredients) ? recipe.additionalIngredients : [],
          steps: Array.isArray(recipe.steps) ? recipe.steps : [{
            materials: [{ name: '', amount: '' }],
            desc: '',
            result: '',
            resultName: '',
            time: ''
          }]
        };
        
        this.setData({ recipe: recipeWithDefaults }, () => {
          // 加载完成后同步所有步骤材料
          this.syncAllStepMaterials();
        });
        console.log('加载配方成功:', recipeWithDefaults);
      } else {
        // 如果找不到配方，显示默认数据
        const defaultRecipe = {
          id: 101,
          name: '提拉米苏',
          category: '甜点',
          difficulty: '中等',
          time: '45分钟',
          mainIngredients: [
            { name: '马斯卡彭奶酪', amount: '250g', unit: 'g' },
            { name: '手指饼干', amount: '150g', unit: 'g' },
            { name: '咖啡', amount: '150ml', unit: 'ml' },
            { name: '蛋黄', amount: '4个', unit: '个' }
          ],
          additionalIngredients: [
            { name: '白砂糖', amount: '60g', unit: 'g' },
            { name: '可可粉', amount: '10g', unit: 'g' }
          ],
          steps: [
            {
              materials: [{ name: '', amount: '' }],
              desc: '准备一杯浓缩咖啡，加入少量朗姆酒（可选），放凉备用',
              result: '',
              resultName: '',
              time: '5分钟'
            },
            {
              materials: [{ name: '', amount: '' }],
              desc: '分离蛋黄和蛋白，蛋黄中加入三分之一的糖，搅拌至糖溶解，颜色变浅',
              result: '',
              resultName: '',
              time: '5分钟'
            },
            {
              materials: [{ name: '', amount: '' }],
              desc: '加入马斯卡彭奶酪，搅拌均匀成奶酪糊',
              result: '',
              resultName: '',
              time: '3分钟'
            }
          ],
          tips: '1. 手指饼干不要浸泡太久，以免过软影响口感\n2. 可可粉最好在食用前撒，保持表面干爽',
          imageUrl: ''
        };
      
        this.setData({ recipe: defaultRecipe });
        console.log('未找到配方，使用默认数据');
      }
    } catch (error) {
      console.error('加载配方失败:', error);
      wx.showToast({
        title: '加载配方失败',
        icon: 'none'
      });
    }
  },

  // 输入字段变更
  bindInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`recipe.${field}`]: value
    });
  },

  // 材料列表操作
  bindIngredientChange(e) {
    const { index, field, type } = e.currentTarget.dataset;
    const { value } = e.detail;
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 如果是修改用量，检查是否需要添加单位
    let formattedValue = value;
    if (field === 'amount' && /^\d+(\.\d+)?$/.test(value.trim())) {
      // 如果只有数字，添加"g"单位
      formattedValue = value.trim() + 'g';
    }
    
    this.setData({
      [`recipe.${key}[${index}].${field}`]: formattedValue
    });
  },

  addIngredient(e) {
    try {
      console.log('添加材料按钮被点击:', e);
      const { type } = e.currentTarget.dataset;
      console.log('材料类型:', type);
      
      if (!type) {
        console.error('未指定材料类型');
        return;
      }

      const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
      
      // 获取当前材料列表
      const currentList = this.data.recipe[key] || [];
      // 创建新的材料列表并添加新项
      const newList = [...currentList, { name: '', amount: '', unit: 'g' }];
      
      console.log('更新前的材料列表:', this.data.recipe[key]);
      console.log('要更新的材料列表:', newList);
      
      // 先直接显示弹窗，避免列表渲染导致的延迟
      const newIndex = newList.length - 1;
      this.setData({
        editorData: {
          type: type,
          index: newIndex,
          name: '',
          amount: '',
          unit: 'g'
        },
        showIngredientEditor: true,
        [`recipe.${key}`]: newList
      });
      
      console.log('材料添加成功，当前材料列表:', this.data.recipe[key]);
      console.log('弹窗状态:', this.data.showIngredientEditor);
    } catch (error) {
      console.error('添加材料失败:', error);
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    }
  },

  // 确认删除材料
  confirmRemoveIngredient(e) {
    // 阻止事件冒泡，防止触发行的点击事件
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    console.log('confirmRemoveIngredient被调用:', e);
    
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { type, index } = e.currentTarget.dataset;
    
    // 打印调试信息
    console.log('确认删除材料:', type, index);
    
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 确保材料列表是一个数组
    if (!Array.isArray(this.data.recipe[key])) {
      console.error('材料列表不是数组:', key);
      return;
    }
    
    // 对主料做特殊检查，至少保留一个
    if (type === 'main' && this.data.recipe[key].length <= 1) {
      wx.showToast({
        title: '至少保留一个主料',
        icon: 'none'
      });
      return;
    }
    
    // 如果是被使用的材料，不允许删除
    if (this.data.recipe[key][index] && this.data.recipe[key][index].used) {
      wx.showToast({
        title: '该材料已在步骤中使用',
        icon: 'none'
      });
      return;
    }
    
    // 确保索引有效
    if (index < 0 || index >= this.data.recipe[key].length) {
      console.error('材料索引无效:', index);
      return;
    }
    
    const materialName = this.data.recipe[key][index].name || `${type === 'main' ? '主料' : '辅料'}${index+1}`;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除${materialName}吗？`,
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          this.removeIngredient(type, index);
        }
      }
    });
  },

  // 删除材料
  removeIngredient(type, index) {
    // 兼容直接从事件调用的情况
    if (typeof type === 'object') {
      const e = type;
      type = e.currentTarget.dataset.type;
      index = e.currentTarget.dataset.index;
    }
    
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 确保材料列表是一个数组
    if (!Array.isArray(this.data.recipe[key])) {
      console.error('材料列表不是数组:', key);
      return;
    }
    
    // 对主料做特殊检查，至少保留一个
    if (type === 'main' && this.data.recipe[key].length <= 1) {
      return;
    }
    
    // 确保索引有效
    if (index < 0 || index >= this.data.recipe[key].length) {
      console.error('材料索引无效:', index);
      return;
    }
    
    const ingredients = [...this.data.recipe[key]];
    ingredients.splice(index, 1);
    
    this.setData({
      [`recipe.${key}`]: ingredients
    }, () => {
      // 确保 updateIngredientsUsageState 在数据更新后调用
      try {
        this.updateIngredientsUsageState();
        
        wx.showToast({
          title: '已删除材料',
          icon: 'success'
        });
      } catch (error) {
        console.error('更新材料状态失败:', error);
      }
    });
  },

  // 步骤列表操作
  bindStepChange(e) {
    const { index, field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`recipe.steps[${index}].${field}`]: value
    });
  },

  // 修改步骤材料
  bindStepMaterialChange(e) {
    const { stepIndex, materialIndex, field } = e.currentTarget.dataset;
    const { value } = e.detail;
    const material = this.data.recipe.steps[stepIndex].materials[materialIndex];
    
    // 如果是引用的材料且正在修改名称或用量，则取消引用标记
    if ((material.reference || material.fromStep !== undefined) && 
        (field === 'name' || field === 'amount')) {
      this.setData({
        [`recipe.steps[${stepIndex}].materials[${materialIndex}].reference`]: false,
        [`recipe.steps[${stepIndex}].materials[${materialIndex}].fromStep`]: undefined,
        [`recipe.steps[${stepIndex}].materials[${materialIndex}].${field}`]: value
      });
    } else {
      // 普通更新
      this.setData({
        [`recipe.steps[${stepIndex}].materials[${materialIndex}].${field}`]: value
      });
    }

    // 材料使用状态仍然实时更新
    this.updateIngredientsUsageState();
  },

  // 材料输入框失去焦点时同步到材料列表
  blurStepMaterialName(e) {
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    const material = this.data.recipe.steps[stepIndex].materials[materialIndex];
    const value = material.name;
    
    // 如果是引用的材料，不需要手动同步
    if (material.reference || material.fromStep !== undefined) {
      return;
    }
    
    // 如果材料名称不为空，同步到主料或辅料列表
    if (value && value.trim()) {
      this.syncMaterialToList(value.trim(), material.unit);
    }
  },
  
  // 材料用量失去焦点时同步到材料列表
  blurStepMaterialAmount(e) {
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    const material = this.data.recipe.steps[stepIndex].materials[materialIndex];
    const name = material.name;
    const amount = material.amount;
    
    // 如果是引用的材料，不需要手动同步用量
    if (material.reference) {
      return;
    }
    
    // 如果材料名称不为空，同步用量到主料或辅料列表
    if (name && name.trim() && amount) {
      this.syncMaterialAmount(name.trim(), amount, material.unit);
    }
  },
  
  // 同步材料用量到列表
  syncMaterialAmount(materialName, amount, unit) {
    if (!materialName || !materialName.trim() || !amount) {
      return;
    }
    
    materialName = materialName.trim();
    
    const mainIngredients = this.data.recipe.mainIngredients || [];
    const additionalIngredients = this.data.recipe.additionalIngredients || [];
    
    // 检查并更新主料中的用量
    let updatedMain = false;
    const updatedMainIngredients = mainIngredients.map(item => {
      if (item.name === materialName) {
        updatedMain = true;
        return { ...item, amount: amount, unit: unit || item.unit };
      }
      return item;
    });
    
    // 检查并更新辅料中的用量
    let updatedAdditional = false;
    const updatedAdditionalIngredients = additionalIngredients.map(item => {
      if (item.name === materialName) {
        updatedAdditional = true;
        return { ...item, amount: amount, unit: unit || item.unit };
      }
      return item;
    });
    
    // 应用更新
    if (updatedMain) {
      this.setData({
        'recipe.mainIngredients': updatedMainIngredients
      });
    }
    
    if (updatedAdditional) {
      this.setData({
        'recipe.additionalIngredients': updatedAdditionalIngredients
      });
    }
  },

  // 修改步骤材料单位
  bindStepMaterialUnitChange(e) {
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    const selectedUnit = this.data.unitOptions[e.detail.value];
    
    this.setData({
      [`recipe.steps[${stepIndex}].materials[${materialIndex}].unit`]: selectedUnit
    }, () => {
      // 更新完单位后，同步到材料列表
      const material = this.data.recipe.steps[stepIndex].materials[materialIndex];
      if (material && material.name && material.name.trim()) {
        if (material.amount) {
          // 如果有用量，同步用量和单位
          this.syncMaterialAmount(material.name.trim(), material.amount, selectedUnit);
        } else {
          // 如果只有名称，只更新单位
          this.syncMaterialUnit(material.name.trim(), selectedUnit);
        }
      }
    });
  },
  
  // 同步材料单位到列表
  syncMaterialUnit(materialName, unit) {
    if (!materialName || !materialName.trim() || !unit) {
      return;
    }
    
    materialName = materialName.trim();
    
    const mainIngredients = this.data.recipe.mainIngredients || [];
    const additionalIngredients = this.data.recipe.additionalIngredients || [];
    
    // 检查并更新主料中的单位
    let updatedMain = false;
    const updatedMainIngredients = mainIngredients.map(item => {
      if (item.name === materialName) {
        updatedMain = true;
        return { ...item, unit };
      }
      return item;
    });
    
    // 检查并更新辅料中的单位
    let updatedAdditional = false;
    const updatedAdditionalIngredients = additionalIngredients.map(item => {
      if (item.name === materialName) {
        updatedAdditional = true;
        return { ...item, unit };
      }
      return item;
    });
    
    // 应用更新
    if (updatedMain) {
      this.setData({
        'recipe.mainIngredients': updatedMainIngredients
      });
    }
    
    if (updatedAdditional) {
      this.setData({
        'recipe.additionalIngredients': updatedAdditionalIngredients
      });
    }
  },

  // 同步材料到列表 - 增强版
  syncMaterialToList(materialName, materialUnit) {
    // 如果材料名为空，不进行同步
    if (!materialName || !materialName.trim()) {
      return;
    }
    
    materialName = materialName.trim();
    
    const mainIngredients = this.data.recipe.mainIngredients || [];
    const additionalIngredients = this.data.recipe.additionalIngredients || [];

    // 检查是否已存在于主料或辅料中
    const existsInMain = mainIngredients.some(item => item.name === materialName);
    const existsInAdditional = additionalIngredients.some(item => item.name === materialName);

    // 如果都不存在，添加到主料列表
    if (!existsInMain && !existsInAdditional) {
      console.log('添加新材料到主料列表:', materialName);
      mainIngredients.push({
        name: materialName,
        amount: '',
        unit: materialUnit || 'g',
        used: true
      });

      this.setData({
        'recipe.mainIngredients': mainIngredients
      });
    }
  },
  
  // 检查并同步所有步骤材料
  syncAllStepMaterials() {
    const steps = this.data.recipe.steps || [];
    
    // 收集所有步骤中使用的材料名称
    steps.forEach(step => {
      if (step && step.materials && Array.isArray(step.materials)) {
        step.materials.forEach(material => {
          if (material && material.name && material.name.trim()) {
            // 同步材料名称到列表
            this.syncMaterialToList(material.name, material.unit);
            
            // 同步材料用量到列表
            if (material.amount) {
              this.syncMaterialAmount(material.name, material.amount, material.unit);
            }
          }
        });
      }
    });
    
    // 更新材料使用状态
    this.updateIngredientsUsageState();
  },

  // 更新材料使用状态
  updateIngredientsUsageState() {
    const steps = this.data.recipe.steps || [];
    const mainIngredients = this.data.recipe.mainIngredients || [];
    const additionalIngredients = this.data.recipe.additionalIngredients || [];

    // 收集所有步骤中使用的材料名称
    const usedMaterials = new Set();
    steps.forEach(step => {
      if (step && step.materials && Array.isArray(step.materials)) {
        step.materials.forEach(material => {
          if (material && material.name && material.name.trim()) {
            usedMaterials.add(material.name.trim());
          }
        });
      }
    });

    console.log('已使用的材料列表:', Array.from(usedMaterials));

    // 更新主料使用状态
    const updatedMainIngredients = mainIngredients.map(item => ({
      ...item,
      used: item && item.name ? usedMaterials.has(item.name) : false
    }));

    // 更新辅料使用状态
    const updatedAdditionalIngredients = additionalIngredients.map(item => ({
      ...item,
      used: item && item.name ? usedMaterials.has(item.name) : false
    }));

    this.setData({
      'recipe.mainIngredients': updatedMainIngredients,
      'recipe.additionalIngredients': updatedAdditionalIngredients
    });
  },

  // 获取之前步骤的结果列表
  getPreviousResults(currentStepIndex) {
    const previousResults = [];
    const steps = this.data.recipe.steps;
    
    // 处理无效参数情况
    if (!steps || typeof currentStepIndex !== 'number') {
      return [];
    }
    
    for (let i = 0; i < currentStepIndex; i++) {
      if (steps[i] && steps[i].resultName) {
        previousResults.push({
          stepIndex: i,
          resultName: steps[i].resultName,
          result: steps[i].result
        });
      }
    }
    
    return previousResults;
  },

  // 选择之前步骤的结果作为材料
  selectPreviousResult(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    
    if (!this.data.recipe.steps || !this.data.recipe.steps[stepIndex]) {
      console.error('步骤不存在:', stepIndex);
      return;
    }
    
    const previousResults = this.getPreviousResults(stepIndex);
    
    if (!previousResults || previousResults.length === 0) {
      wx.showToast({
        title: '没有可选择的结果',
        icon: 'none'
      });
      return;
    }
    
    const items = previousResults.map(item => `步骤${item.stepIndex + 1}: ${item.resultName}`);
    
    wx.showActionSheet({
      itemList: items,
      success: (res) => {
        if (res.tapIndex === undefined || !previousResults[res.tapIndex]) {
          return;
        }
        
        const selectedResult = previousResults[res.tapIndex];
        const steps = [...this.data.recipe.steps];
        
        if (!steps[stepIndex] || !steps[stepIndex].materials) {
          console.error('材料列表不存在');
          return;
        }
        
        if (!steps[stepIndex].materials[materialIndex]) {
          console.error('材料不存在:', materialIndex);
          return;
        }
        
        const resultName = selectedResult.resultName || '';
        const currentUnit = steps[stepIndex].materials[materialIndex].unit || 'g';
        
        // 设置默认用量为1
        const defaultAmount = '1';
        
        steps[stepIndex].materials[materialIndex] = {
          name: resultName,
          amount: defaultAmount,
          unit: currentUnit,
          fromStep: selectedResult.stepIndex
        };
        
        this.setData({
          'recipe.steps': steps
        }, () => {
          // 同步到材料列表
          if (resultName) {
            this.syncMaterialToList(resultName, currentUnit);
            // 同时同步默认用量
            this.syncMaterialAmount(resultName, defaultAmount, currentUnit);
          }
        });
      }
    });
  },

  // 添加步骤材料
  addStepMaterial(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { stepIndex } = e.currentTarget.dataset;
    
    if (!Array.isArray(this.data.recipe.steps)) {
      console.log('初始化步骤数组');
      this.setData({
        'recipe.steps': [{
          materials: [{ name: '', amount: '', unit: 'g' }],
          desc: '',
          result: '',
          resultName: '',
          time: ''
        }]
      });
      return;
    }
    
    const steps = [...this.data.recipe.steps];
    
    if (!steps[stepIndex]) {
      console.error('步骤不存在:', stepIndex);
      return;
    }
    
    // 确保materials是一个数组
    if (!steps[stepIndex].materials) {
      console.log('初始化材料数组');
      steps[stepIndex].materials = [];
    }
    
    steps[stepIndex].materials.push({ name: '', amount: '', unit: 'g' });
    
    this.setData({
      'recipe.steps': steps
    });
  },

  // 确认删除步骤
  confirmRemoveStep(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { index } = e.currentTarget.dataset;
    
    // 确保steps是一个数组
    if (!Array.isArray(this.data.recipe.steps) || this.data.recipe.steps.length <= 1) {
      return; // 至少保留一个步骤
    }
    
    // 确保索引有效
    if (index < 0 || index >= this.data.recipe.steps.length) {
      console.error('步骤索引无效:', index);
      return;
    }
    
    const step = this.data.recipe.steps[index];
    if (!step) {
      console.error('步骤不存在:', index);
      return;
    }
    
    const stepDesc = step.desc || `步骤 ${index + 1}`;
    const displayName = stepDesc.length > 10 ? stepDesc.substring(0, 10) + '...' : stepDesc;

    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${displayName}"吗？`,
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          this.removeStep(index);
        }
      }
    });
  },

  // 删除步骤
  removeStep(index) {
    if (typeof index !== 'number') {
      // 兼容直接从事件调用的情况
      if (index && index.currentTarget) {
        index = index.currentTarget.dataset.index;
      } else {
        console.error('无效的索引:', index);
        return;
      }
    }
    
    // 确保steps是一个数组
    if (!Array.isArray(this.data.recipe.steps) || this.data.recipe.steps.length <= 1) {
      return; // 至少保留一个步骤
    }
    
    // 确保索引有效
    if (index < 0 || index >= this.data.recipe.steps.length) {
      console.error('步骤索引无效:', index);
      return;
    }
    
    const steps = [...this.data.recipe.steps];
    steps.splice(index, 1);
    
    this.setData({
      'recipe.steps': steps
    }, () => {
      // 确保 updateIngredientsUsageState 在数据更新后调用
      try {
        // 确保在this.data.recipe.steps正确初始化后再调用
        if (Array.isArray(this.data.recipe.steps)) {
          this.updateIngredientsUsageState();
        }
        
        wx.showToast({
          title: '已删除步骤',
          icon: 'success'
        });
      } catch (error) {
        console.error('更新材料状态失败:', error);
      }
    });
  },

  // 下拉选择器
  bindCategoryChange(e) {
    const selectedIndex = e.detail.value;
    const categoryId = this.data.categories[selectedIndex].id;
    const categoryName = this.data.categories[selectedIndex].name;
    
    this.setData({
      'recipe.categoryId': categoryId,
      'recipe.category': categoryName
    });
  },

  bindDifficultyChange(e) {
    this.setData({
      'recipe.difficulty': this.data.difficultyOptions[e.detail.value]
    });
  },

  // 图片选择
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          'recipe.imageUrl': res.tempFiles[0].tempFilePath
        });
      }
    });
  },

  // 表单提交
  saveRecipe() {
    // 在保存前确保所有步骤材料都已同步到材料列表
    this.syncAllStepMaterials();
    
    // 表单验证
    if (!this.data.recipe.name.trim()) {
      wx.showToast({
        title: '请输入配方名称',
        icon: 'none'
      });
      return;
    }

    if (!this.data.recipe.categoryId) {
      wx.showToast({
        title: '请选择配方分类',
        icon: 'none'
      });
      return;
    }

    // 确保主料是一个数组
    if (!Array.isArray(this.data.recipe.mainIngredients) || this.data.recipe.mainIngredients.length === 0) {
      wx.showToast({
        title: '请添加至少一个主料',
        icon: 'none'
      });
      return;
    }

    // 检查是否有空的主料
    const hasEmptyMainIngredient = this.data.recipe.mainIngredients.some(
      item => !item.name.trim() || !item.amount.trim()
    );
    if (hasEmptyMainIngredient) {
      wx.showToast({
        title: '请完善主料信息',
        icon: 'none'
      });
      return;
    }

    // 确保步骤是一个数组
    if (!Array.isArray(this.data.recipe.steps) || this.data.recipe.steps.length === 0) {
      wx.showToast({
        title: '请添加至少一个步骤',
        icon: 'none'
      });
      return;
    }

    // 检查是否有空的步骤
    const hasEmptyStep = this.data.recipe.steps.some(
      item => !item.desc.trim()
    );
    if (hasEmptyStep) {
      wx.showToast({
        title: '请完善制作步骤',
        icon: 'none'
      });
      return;
    }

    // 保存配方
    wx.showLoading({
      title: '保存中...',
      mask: true // 防止用户重复点击
    });

    try {
      // 准备要保存的配方对象
      const recipeToSave = {
        ...this.data.recipe,
        // 确保基本字段存在且格式正确
        name: (this.data.recipe.name || '').trim(),
        categoryId: (this.data.recipe.categoryId || '').toString(),
        difficulty: this.data.recipe.difficulty || '中等',
        time: this.data.recipe.time || '',
        tips: this.data.recipe.tips || '',
        imageUrl: this.data.recipe.imageUrl || ''
      };
      
      // 获取分类名称
      const category = this.data.categories.find(c => c.id.toString() === recipeToSave.categoryId);
      if (!category) {
        console.error('未找到对应的分类:', recipeToSave.categoryId);
        wx.hideLoading();
        wx.showToast({
          title: '保存失败：未找到对应分类',
          icon: 'none'
        });
        return;
      }
      recipeToSave.category = category.name;
      
      // 确保主料格式正确，没有空项
      recipeToSave.mainIngredients = (this.data.recipe.mainIngredients || [])
        .filter(item => item && item.name && item.name.trim() && item.amount && item.amount.trim())
        .map(item => ({
          name: item.name.trim(),
          amount: item.amount.trim(),
          unit: item.unit || 'g'
        }));
      
      // 确保辅料格式正确，没有空项
      recipeToSave.additionalIngredients = (this.data.recipe.additionalIngredients || [])
        .filter(item => item && item.name && item.name.trim() && item.amount && item.amount.trim())
        .map(item => ({
          name: item.name.trim(),
          amount: item.amount.trim(),
          unit: item.unit || 'g'
        }));
      
      // 确保步骤格式正确，没有空项
      recipeToSave.steps = (this.data.recipe.steps || [])
        .filter(item => item && item.desc && item.desc.trim())
        .map(item => ({
          desc: item.desc.trim(),
          time: (item.time || '').trim(),
          materials: item.materials || [],
          result: item.result || '',
          resultName: item.resultName || ''
        }));
      
      // 确保app.globalData.recipes已初始化为数组
      if (!Array.isArray(app.globalData.recipes)) {
        app.globalData.recipes = [];
      }
      
      // 如果是新建配方，生成一个新ID
      if (!this.data.isEdit) {
        // 获取所有配方，找到最大ID
        const allRecipes = app.globalData.recipes || [];
        let maxId = 0;
        if (allRecipes.length > 0) {
          maxId = Math.max(...allRecipes.map(r => Number(r.id) || 0));
        }
        recipeToSave.id = maxId + 1;
        
        // 添加创建时间
        recipeToSave.createTime = new Date().toISOString();
        
        // 添加到全局数据
        app.globalData.recipes.push(recipeToSave);
        
        console.log('新建配方成功:', recipeToSave);
      } else {
        // 更新已有配方
        const recipeIndex = app.globalData.recipes.findIndex(r => 
          r.id.toString() === this.data.recipeId.toString()
        );
        
        // 保留原有创建时间
        if (recipeIndex !== -1) {
          recipeToSave.createTime = app.globalData.recipes[recipeIndex].createTime;
          recipeToSave.updateTime = new Date().toISOString();
          app.globalData.recipes[recipeIndex] = recipeToSave;
          
          console.log('更新配方成功:', recipeToSave);
        } else {
          // 如果找不到对应ID的配方，作为新配方添加
          recipeToSave.id = this.data.recipeId || Date.now();
          recipeToSave.createTime = new Date().toISOString();
          app.globalData.recipes.push(recipeToSave);
          
          console.log('未找到原配方，作为新配方添加:', recipeToSave);
        }
      }
      
      // 保存到本地存储
      try {
        app.saveLocalData();
        console.log('本地存储保存成功');
      } catch (error) {
        console.error('本地存储保存失败:', error);
        wx.hideLoading();
        wx.showToast({
          title: '保存失败：无法写入存储',
          icon: 'none'
        });
        return;
      }
      
      // 保存成功后的处理
      wx.hideLoading();
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          // 延迟返回，确保用户看到成功提示
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    } catch (error) {
      console.error('保存配方失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  },

  // 取消操作
  cancel() {
    wx.navigateBack();
  },

  // 页面点击事件，用于处理整个页面的点击
  onTapPage(e) {
    // 点击页面空白处时，取消选中的材料
    this.setData({
      selectedIngredient: {
        type: '',
        index: -1
      }
    });
  },

  // 阻止冒泡，防止点击输入框触发父元素的点击事件
  catchTap(e) {
    // 阻止冒泡，保持输入框可编辑
    if (e && e.type && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    return false;
  },

  // 选择材料项
  selectIngredient(e) {
    // 此方法已不再被新的表格视图直接调用，但保留以兼容其他功能
    // 添加调试信息
    console.log('材料项被点击:', e);
    
    // 防止input触发材料项选择
    if (e && e.target && e.target.nodeName === 'INPUT') {
      console.log('忽略INPUT元素的点击');
      return;
    }
    
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { type, index } = e.currentTarget.dataset;
    const idx = parseInt(index);
    
    console.log('打开材料编辑弹窗:', type, idx);
    
    // 直接打开编辑弹窗
    this.openMaterialEditor(type, idx);
  },
  
  // 打开材料编辑弹窗（新增辅助函数）
  openMaterialEditor(type, index) {
    console.log('执行openMaterialEditor:', type, index);
    
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 确保索引有效
    if (!this.data.recipe[key] || index < 0 || index >= this.data.recipe[key].length) {
      console.error('材料不存在:', type, index);
      return;
    }
    
    const ingredient = this.data.recipe[key][index];
    console.log('获取到材料数据:', ingredient);
    
    // 获取材料单位，如果存在，否则使用默认单位
    let amount = ingredient.amount || '';
    let unit = ingredient.unit || 'g';
    
    this.setData({
      editorData: {
        type,
        index,
        name: ingredient.name || '',
        amount: amount,
        unit: unit
      },
      showIngredientEditor: true
    }, () => {
      console.log('编辑弹窗已显示:', this.data.showIngredientEditor);
    });
  },

  // 打开材料编辑弹窗
  openIngredientEditor(e) {
    // 阻止事件冒泡
    if (e && typeof e.stopPropagation === 'function') {
      e.stopPropagation();
    }
    
    console.log('openIngredientEditor被调用:', e);
    
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { type, index } = e.currentTarget.dataset;
    
    // 打印调试信息
    console.log('打开材料编辑弹窗:', type, index);
    
    // 调用编辑器打开函数
    this.openMaterialEditor(type, index);
  },
  
  // 编辑器输入框变更
  bindEditorInput(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`editorData.${field}`]: value
    });
  },
  
  // 关闭材料编辑弹窗
  closeIngredientEditor() {
    console.log('关闭材料编辑弹窗');
    this.setData({
      showIngredientEditor: false
    });
    
    // 如果是新添加的空材料但没有填写内容，需要清除
    const { type, index, name } = this.data.editorData;
    if (index !== undefined && type && name === '') {
      const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
      const list = [...this.data.recipe[key]];
      
      // 判断是否为空材料（新添加但没填内容）
      if (list[index] && (!list[index].name || list[index].name.trim() === '')) {
        list.splice(index, 1);
        this.setData({
          [`recipe.${key}`]: list
        });
      }
    }
  },
  
  // 编辑器单位选择
  bindUnitChange(e) {
    const selectedUnit = this.data.unitOptions[e.detail.value];
    this.setData({
      'editorData.unit': selectedUnit
    });
  },
  
  // 保存材料编辑
  saveIngredientEdit() {
    const { type, index, name, amount, unit } = this.data.editorData;
    
    if (!name.trim()) {
      wx.showToast({
        title: '请输入材料名称',
        icon: 'none'
      });
      return;
    }
    
    if (!amount.trim()) {
      wx.showToast({
        title: '请输入用量',
        icon: 'none'
      });
      return;
    }
    
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 确保材料列表已初始化
    if (!Array.isArray(this.data.recipe[key])) {
      this.setData({
        [`recipe.${key}`]: []
      });
    }
    
    // 确保索引有效
    const list = [...this.data.recipe[key]];
    if (index < 0 || index >= list.length) {
      // 如果索引无效，添加到末尾
      list.push({
        name: name.trim(),
        amount: amount.trim(),
        unit: unit
      });
    } else {
      // 更新已有项
      list[index] = {
        ...list[index],
        name: name.trim(),
        amount: amount.trim(),
        unit: unit
      };
    }
    
    this.setData({
      [`recipe.${key}`]: list,
      showIngredientEditor: false
    });
    
    console.log('保存材料成功:', list);
    
    // 更新材料使用状态
    this.updateIngredientsUsageState();
  },
  
  // 从编辑弹窗中删除材料
  deleteIngredientFromEditor() {
    const { type, index } = this.data.editorData;
    const key = type === 'main' ? 'mainIngredients' : 'additionalIngredients';
    
    // 检查是否允许删除
    if (type === 'main' && this.data.recipe[key].length <= 1) {
      wx.showToast({
        title: '至少保留一个主料',
        icon: 'none'
      });
      return;
    }
    
    // 检查材料是否被使用
    if (this.data.recipe[key][index] && this.data.recipe[key][index].used) {
      wx.showToast({
        title: '该材料已在步骤中使用',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此材料吗？',
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          // 关闭弹窗
          this.setData({
            showIngredientEditor: false
          });
          
          // 删除材料
          this.removeIngredient(type, index);
        }
      }
    });
  },

  // 确认删除步骤材料
  confirmRemoveStepMaterial(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    const steps = this.data.recipe.steps;
    
    if (!Array.isArray(steps) || !steps[stepIndex]) {
      console.error('步骤不存在:', stepIndex);
      return;
    }
    
    if (!Array.isArray(steps[stepIndex].materials) || !steps[stepIndex].materials[materialIndex]) {
      console.error('材料不存在:', stepIndex, materialIndex);
      return;
    }
    
    if (steps[stepIndex].materials.length <= 1) {
      return; // 至少保留一个材料
    }
    
    const materialName = steps[stepIndex].materials[materialIndex].name || `材料${materialIndex+1}`;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除步骤${stepIndex+1}的${materialName}吗？`,
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          this.removeStepMaterial(stepIndex, materialIndex);
        }
      }
    });
  },

  // 删除步骤材料
  removeStepMaterial(stepIndex, materialIndex) {
    // 兼容直接从事件调用的情况
    if (typeof stepIndex === 'object') {
      const e = stepIndex;
      stepIndex = e.currentTarget.dataset.stepIndex;
      materialIndex = e.currentTarget.dataset.materialIndex;
    }
    
    // 确保steps是数组且索引有效
    if (!Array.isArray(this.data.recipe.steps) || 
        stepIndex < 0 || 
        stepIndex >= this.data.recipe.steps.length) {
      console.error('步骤索引无效:', stepIndex);
      return;
    }
    
    const steps = [...this.data.recipe.steps];
    
    // 确保步骤的materials是数组且索引有效
    if (!Array.isArray(steps[stepIndex].materials) || 
        materialIndex < 0 || 
        materialIndex >= steps[stepIndex].materials.length) {
      console.error('材料索引无效:', materialIndex);
      return;
    }
    
    if (steps[stepIndex].materials.length > 1) {
      steps[stepIndex].materials.splice(materialIndex, 1);
      
      this.setData({
        'recipe.steps': steps
      }, () => {
        // 确保 updateIngredientsUsageState 在数据更新后调用
        try {
          this.updateIngredientsUsageState();
          
          wx.showToast({
            title: '已删除材料',
            icon: 'success'
          });
        } catch (error) {
          console.error('更新材料状态失败:', error);
        }
      });
    }
  },

  // 添加步骤
  addStep() {
    try {
      console.log('添加步骤按钮被点击');
      console.log('当前步骤列表:', this.data.recipe.steps);
      
      // 确保steps是一个数组
      const currentSteps = Array.isArray(this.data.recipe.steps) ? this.data.recipe.steps : [];
      const steps = [...currentSteps, {
        materials: [{ name: '', amount: '' }],
        desc: '',
        result: '',
        resultName: '',
        time: ''
      }];
      
      console.log('要更新的步骤列表:', steps);
      
      this.setData({
        'recipe.steps': steps
      }, () => {
        console.log('步骤添加成功，当前步骤列表:', this.data.recipe.steps);
      });
    } catch (error) {
      console.error('添加步骤失败:', error);
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    }
  },

  // 从材料列表中选择材料
  selectMaterialFromList(e) {
    if (!e || !e.currentTarget || !e.currentTarget.dataset) {
      console.error('事件对象不完整', e);
      return;
    }
    
    const { stepIndex, materialIndex } = e.currentTarget.dataset;
    
    // 获取所有材料
    const mainIngredients = this.data.recipe.mainIngredients || [];
    const additionalIngredients = this.data.recipe.additionalIngredients || [];
    
    // 合并主料和辅料
    const allIngredients = [
      ...mainIngredients.map(item => ({
        ...item,
        type: '主料'
      })),
      ...additionalIngredients.map(item => ({
        ...item,
        type: '辅料'
      }))
    ];
    
    // 获取当前步骤已使用的材料名称
    const currentStepMaterials = this.data.recipe.steps[stepIndex].materials || [];
    const usedMaterialNames = new Set(
      currentStepMaterials
        .filter(m => m && m.name)
        .map(m => m.name)
    );
    
    // 过滤已在当前步骤中使用的材料
    const unusedIngredients = allIngredients.filter(item => !usedMaterialNames.has(item.name));
    
    // 如果没有未使用的材料，提示用户
    if (unusedIngredients.length === 0) {
      wx.showToast({
        title: '所有材料已使用',
        icon: 'none'
      });
      return;
    }
    
    // 构建菜单项
    const menuItems = unusedIngredients.map(item => `${item.type}: ${item.name} (${item.amount})`);
    
    // 获取之前步骤的结果
    const previousResults = this.getPreviousResults(stepIndex);
    if (previousResults && previousResults.length > 0) {
      // 过滤已使用的步骤结果
      const unusedResults = previousResults.filter(result => !usedMaterialNames.has(result.resultName));
      
      // 添加未使用的步骤结果到菜单
      unusedResults.forEach(result => {
        menuItems.push(`步骤${result.stepIndex + 1}结果: ${result.resultName}`);
      });
    }
    
    // 如果没有可选项，提示用户
    if (menuItems.length === 0) {
      wx.showToast({
        title: '没有可选材料',
        icon: 'none'
      });
      return;
    }
    
    // 显示操作菜单
    wx.showActionSheet({
      itemList: menuItems,
      success: (res) => {
        const selectedIndex = res.tapIndex;
        
        if (selectedIndex < unusedIngredients.length) {
          // 用户选择了材料
          const selectedMaterial = unusedIngredients[selectedIndex];
          
          // 更新步骤中的材料
          const steps = [...this.data.recipe.steps];
          if (!steps[stepIndex] || !steps[stepIndex].materials) {
            console.error('材料列表不存在');
            return;
          }
          
          // 更新材料
          steps[stepIndex].materials[materialIndex] = {
            name: selectedMaterial.name,
            amount: selectedMaterial.amount,
            unit: selectedMaterial.unit,
            reference: true  // 标记为引用的材料
          };
          
          this.setData({
            'recipe.steps': steps
          }, () => {
            // 更新材料使用状态
            this.updateIngredientsUsageState();
          });
        } else if (previousResults && previousResults.length > 0) {
          // 用户选择了步骤结果
          const unusedResults = previousResults.filter(result => !usedMaterialNames.has(result.resultName));
          const resultIndex = selectedIndex - unusedIngredients.length;
          const selectedResult = unusedResults[resultIndex];
          
          // 更新步骤中的材料
          const steps = [...this.data.recipe.steps];
          if (!steps[stepIndex] || !steps[stepIndex].materials) {
            console.error('材料列表不存在');
            return;
          }
          
          const resultName = selectedResult.resultName || '';
          const currentUnit = steps[stepIndex].materials[materialIndex].unit || 'g';
          
          // 设置默认用量为1
          const defaultAmount = '1';
          
          steps[stepIndex].materials[materialIndex] = {
            name: resultName,
            amount: defaultAmount,
            unit: currentUnit,
            fromStep: selectedResult.stepIndex
          };
          
          this.setData({
            'recipe.steps': steps
          }, () => {
            // 同步到材料列表
            if (resultName) {
              this.syncMaterialToList(resultName, currentUnit);
              // 同时同步默认用量
              this.syncMaterialAmount(resultName, defaultAmount, currentUnit);
            }
          });
        }
      }
    });
  }
}); 